// pages/biz/auctionDetail/auctionDetail.js
// --------秒杀---------2019.6.10更新
//   1，报名
// 2，支付报名费
// 3，等待活动开始
// 4，立即抢购
// 5，立即抢购（灰色按钮）
// 6，支付订金
// 7，已售空 
// 8，活动已结束
// ------竞拍---------2019.6.10更新
//   1，报名
// 2，支付报名费
// 3，等待活动开始
// 4，叫价
// 5，支付订金
// 6，活动结束
// 1，2，3是属于房源类商品，4，5，6，7是属于普通商品吧
let goodsList = [
  { actEndTime: '2018-11-11 10:00:43' },
]
//引入请求接口文件
import Serv from './auctionDetailServ';
var regeneratorRuntime = require("../../../../lib/js/runtime-module.js")
var WxParse = require('../../../../wxParse/wxParse.js');
import util from '../../../../utils/util2'
let propertyType = {
  11: "住宅", 12: "公寓", 21: "地上停车位", 22: "地下停车位（非人防）", 23: "地下停车位（人防）", 24: '地下车库',
  25: '地上车库', 31: "地上商铺", 32: "地下商铺", 33: '地上集中商业',
  34: '地下集中商业',
}

Page({

  /**
   * 页面的初始数据 
   */
  data: {
    imgUrls: [],
    mBox: false,
    changepx: "160rpx",
    countDownList: [],
    actEndTimeList: [],
    like: true,
    auctionDetail:{},
    action:1,
    attrList:[],
    maxPrice:'',
    current:1,
    endTime:'',
    startTime:'',
    productDeType: [4, 5, 6, 7],
    productHouseType: [1, 2, 3]
  },
  goTo(e) {
    wx.navigateTo({
      url: `../../findHouse/estateAllDetail/estateAllDetail?productId=${e.currentTarget.dataset.id}`,
    })
  },
  swiperChange(e) {
    this.setData({ current: e.detail.current + 1 })
  },
  //routerGo
  routerGo(e){
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url,
    })
  },
  //-加载当前竞拍最高价
  async queryCurrentDetail(parmas, cbk) {
    let { data } = await Serv.queryCurrentDetail(parmas)
    
    this.setData({
      maxPrice: data.price,
      attrList: data.avatars,
      userCount: data.userCount,
      stock:data.stock,
      mobile: data.mobile ? util.hidePhone(data.mobile) : ''
    })
    // console.log(this.data.maxPrice)
    cbk && cbk(data)
  },
  //点击关注
  async attention(e){
    let { follow ,auctionDetail} =this.data
    if (follow == 0) {
     follow = 1
    } else {
      follow = 0
    }
    this.setData({
      follow
    })
    // console.log(e.currentTarget.dataset.follow)
    
    let { data, success } = await Serv.createFavorite({
      seckillProductId: auctionDetail.seckillProductId, type: 4, follow,
       })
    
  },
  //判断是否绑定钱包
  //判断是否绑定钱包
  async flagMoney({ }) {
    let { data, success } = await Serv.flagMoney({})
    let { auctionDetail } = this.data
    if (success) {
      if (data) {
        wx.navigateTo({
          url: `../../pay/payment/payment?actionType=3&seckillProductId=${auctionDetail.seckillProductId}`,
        })
      } else {
        wx.showModal({
          title: '温馨提示',
          content: '请您先绑定钱包',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateTo({
                url: `../../wallet/index/index`,
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  },
  // 请求详情
  async getAuctionDetail(parmas,cbk) {
    let { data,success,msg} = await Serv.getAuctionDetail(parmas)
    if(success){
      let startTime = data.startTime.slice(0, -3).replace(/-/g, ".")
      let endTime = data.endTime.slice(0, -3).replace(/-/g, ".")
      data.propertyType = propertyType[data.propertyType]
      console.log(data.imageUrls)
      WxParse.wxParse('content', 'html', data.productDesc, this, 0)
      this.setData({
        auctionDetail: data,
        imgUrls: data.imageUrls,
        accountId: '123',
        follow: data.follow,
        startTime,
        endTime,
      })
      wx.setStorageSync('currentDetail', data)
      cbk && cbk(data)
    }else{
      wx.showToast({
        title: msg,
        icon:"none"
      })
    }
    
  },
  getAllDetail(){
    let { seckillProductId} = this.data
    wx.navigateTo({
      url: `../../findHouse/estateAllDetail/estateAllDetail?id=${seckillProductId}`,
    })
  },
  showBox: function () {
    this.setData({ mBox: !this.data.mBox })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad(opt) {
    /*-----------节点---------------*/ 
    //1为竞拍开始 2为未开始
    let follow = opt.follow
    this.setData({
      action:opt.action,
      seckillProductId:opt.id,
      productId: opt.pid,
      follow
    })
    this.queryCurrentDetail({ productId: opt.pid, seckillProductId: opt.id, sellType: 2 })
    //将计时器赋值给setInter
    this.data.setInter=setInterval(()=>{
      this.queryCurrentDetail({ productId: opt.pid, seckillProductId: opt.id, sellType: 2 })
    },10000)
    
    this.getAuctionDetail(opt.id,(data)=>{
      console.log(data,'detail')
      
      let goodsList
      if (data.isStartActivity==2){
         goodsList = [{ actEndTime: data.endTime }]
        
      } else if (data.isStartActivity == 1){
         goodsList = [{ actEndTime: data.startTime }]
      }
      //倒计时
      let endTimeList = [];
      goodsList&&goodsList.forEach(o => { endTimeList.push(o.actEndTime) })
      this.setData({ actEndTimeList: endTimeList });
    })
    
    console.log(this.data.countDownList)
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  toMap() {
    wx.openLocation({
      latitude: Number(this.data.auctionDetail.latitude),
      longitude: Number(this.data.auctionDetail.longitude),
      name: this.data.auctionDetail.address
    })
  },
  onShow: function () {
    // 执行倒计时函数
    this.countDown();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },
  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.actEndTimeList;
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = util.dateFromString(o).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理 
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
      } else {//活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      countDownArr.push(obj);
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ countDownList: countDownArr })
    setTimeout(this.countDown, 1000);
  },
  phone: function (e) {
    let { auctionDetail } = this.data
    wx.makePhoneCall({
      phoneNumber: auctionDetail.mobile
    })
  },
 
  onUnload: function () {
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    let { productId, seckillProductId} =  this.data
    this.queryCurrentDetail({ productId, seckillProductId, sellType: 2 })
    //模拟加载
    setTimeout(function () {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1000);
  },
  // 报名
  enroll: function (e) {
    let activityType = e.currentTarget.dataset.activitytype
    let { seckillProductId } = this.data.auctionDetail
    this.getEnroll({ activityType, seckillProductId })
  },
  async getEnroll(parmas) {
    let { data, msg, success } = await Serv.enroll(parmas)
    let auctionDetail = this.data.auctionDetail
    if (success) {
      this.setData({
        tips: `提示：活动将在${util.dateChina(auctionDetail.startTime)}开始！`,
        flagEnroll: data
      }, () => {
        //需求临时变更加个判断
        if(data){
          this.showDialog()
        }else{
          let url = `/pages/biz/pay/payment/payment?actionType=3&seckillProductId=${auctionDetail.seckillProductId}`
          this.getAuctionDetail(auctionDetail.seckillProductId)
          wx.navigateTo({
            url: url,
          })
        }
      })
    } else {
      wx.showToast({
        title: msg,
        icon: 'none'
      })
    }

  },
  onReady: function () {
    //获得dialog组件
    this.dialog = this.selectComponent("#dialog");
    //this.showDialog()
  },
  showDialog() {
    this.dialog.showDialog();
  },
  hide() {
    this.dialog.hideDialog();
  },
  //取消事件
  _onCancel() {
    console.log('你点击了取消');
    let { auctionDetail } = this.data
    this.dialog.hideDialog();
    this.getAuctionDetail(auctionDetail.seckillProductId)
  },
  //确认事件
  _onOk() {
    console.log('你点击了确定');
    this.dialog.hideDialog();
    let { auctionDetail } = this.data
    let url = `/pages/biz/pay/payment/payment?actionType=3&seckillProductId=${auctionDetail.seckillProductId}`
    this.getAuctionDetail(auctionDetail.seckillProductId)
    wx.navigateTo({
      url: url,
    })
  },
})